//
//  HomeViewController.m
//  phoneTool
//
//  Created by HappyMilk 02 on 2017/7/20.
//  Copyright © 2017年 tomi. All rights reserved.
//

#import "HomeViewController.h"
#import "LoginHeader.h"
#import "HomeViewCell.h"
#import "NewsViewController.h"
#import "DDQRCodeViewController.h"
#import "MemoryViewController.h"
#import "BatteryViewController.h"
#import "HHToolsViewController.h"
#import "WifiSpeedController.h"
#import "ScreenTestController.h"
#import "AFNetworking.h"
#import "MJUserModel.h"
#import "UIImageView+WebCache.h"
#import "MJMyMsgController.h"
#import "LoginViewController.h"
#import "sys/utsname.h"
#import "HardwareController.h"


@interface HomeViewController ()

@property (weak, nonatomic) IBOutlet UIView *view_scroll_content;

@property (weak, nonatomic) IBOutlet UIImageView *imgv_head;

@property (weak, nonatomic) IBOutlet UILabel *lab_username;
@property (weak, nonatomic) IBOutlet UILabel *lab_phoneModel;

@property (weak, nonatomic) IBOutlet UIView *view_list;
@property (weak, nonatomic) IBOutlet UIView *view_shadow;

@property (weak, nonatomic) IBOutlet UILabel *lab_dian;
@property (weak, nonatomic) IBOutlet UILabel *lab_dian_use;
@property (weak, nonatomic) IBOutlet UILabel *lab_adr;
@property (weak, nonatomic) IBOutlet UILabel *lab_temp;
@property (weak, nonatomic) IBOutlet UILabel *lab_pm25;

@property (nonatomic ,strong) MJUserModel *userModel;
@property (weak, nonatomic) IBOutlet UILabel *lab_battery;

@end

@implementation HomeViewController


- (IBAction)openurlstr:(UIButton *)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://weather1.sina.cn/"]];
}
- (void)appinfoload{
    if (IS_PASS && IS_CHINESE) {
        CGFloat heght = IS_IPAD?90:50;
        GADBannerView *bannerview = [[GADBannerView alloc] initWithAdSize:kGADAdSizeSmartBannerPortrait origin:(CGPoint){0,__kheight-heght}];
        bannerview.adUnitID = @"ca-app-pub-4634576436183649/7109315361";
        bannerview.rootViewController = self.navigationController;
        [self.navigationController.view addSubview:bannerview];
        [bannerview loadRequest:[GADRequest request]];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.lab_battery.text = IS_CHINESE?@"电量":@"BatteryLevel";
    // Do any additional setup after loading the view.
    ADD_OBSERVER(self, @selector(appinfoload), NOTIFICATION_APP_INFO_LOADED, nil);
    

    [self modifyView];
    
    [self tianqiyubaoData];
    
    UIDevice *device = [UIDevice currentDevice];
    device.batteryMonitoringEnabled = YES;

    self.lab_dian.text = [NSString stringWithFormat:@"%.f%%",[self getBatteryQuantity]*100];
    if (!IS_CHINESE) {
        self.lab_dian_use.text = [NSString stringWithFormat:@"Could be used for %.f minutes",[[UIDevice currentDevice] batteryLevel]*1060];
        
    }else{
        self.lab_dian_use.text = [NSString stringWithFormat:@"预计可使用 %.f 分钟",[self getBatteryQuantity]*1060];
    }
}

-(CGFloat)getBatteryQuantity
{
    return [[UIDevice currentDevice] batteryLevel];
}
- (void)tianqiyubaoData{
    
    //NSString *url = [NSString stringWithFormat:@"http://api.avatardata.cn/Weather/Query?key=e998da5e87a4410dab008e39743f412b&cityname=chengdu"];
    NSString *url = @"http://api.avatardata.cn/Weather/Query";
    NSDictionary *dict = @{@"key":@"e998da5e87a4410dab008e39743f412b",@"cityname":@"成都"};
    
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
    [manager POST:url parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        //NSLog(@"dic ----- %@",dic);

        NSString *pm25 = dic[@"result"][@"pm25"][@"pm25"][@"pm25"];
        NSString *ccm = dic[@"result"][@"realtime"][@"weather"][@"temperature"];
        self.lab_temp.text = [NSString stringWithFormat:@"%@℃",ccm];
        self.lab_pm25.text = pm25;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}


- (void)modifyView{

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shadowViewTapAction)];
    [self.view_shadow addGestureRecognizer:tap];
    
    _imgv_head.layer.masksToBounds = YES;
    _imgv_head.layer.cornerRadius = 35;
    
    NSLog(@"型号------ %@",[self iphoneType]);
    self.lab_phoneModel.text = [self iphoneType];
}
- (NSString *)iphoneType {
    
    //需要导入头文件：#import <sys/utsname.h>
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G";
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G";
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G";
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G";
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G";
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad 1G";
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G";
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G";
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G";
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad 4";
    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad 4";
    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad 4";
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPad Air";
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPad Air";
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPad Air";
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G";
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G";
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G";
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    return platform;
}
- (void)shadowViewTapAction{
    
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.view_list.frame = (CGRect){-240,0,240,__kheight};
        self.view_shadow.alpha = 0;
    } completion:^(BOOL finished) {
        self.view_shadow.hidden = YES;
    }];
}

- (void)viewWillDisappear:(BOOL)animated{
    [self shadowViewTapAction];
}
//菜单
- (IBAction)mineList:(UIButton *)sender {
    
    if ([[MyAdTools shareInstance] showInterstitialWithVC:self]) {
        return;
    }
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.view_list.frame = (CGRect){0,0,240,__kheight};
        self.view_shadow.hidden = NO;
        self.view_shadow.alpha = 0.4;
    } completion:^(BOOL finished) {
        
    }];
}
//手机体检
- (IBAction)mobilePhoneTest:(UIButton *)sender {
    
    
}
//8项测试选择
- (IBAction)choiceCategroy:(UIButton *)sender {
    
    if ([[MyAdTools shareInstance] showInterstitialWithVC:self]) {
        return;
    }
    
    if (IS_CHINESE && IS_IPAD && IS_PASS && [[MPWeChat stander] m_needLogin] && ![[MPWeChat stander] m_isLogin]) {
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"login" bundle:nil];
        LoginViewController *vc = [sb instantiateViewControllerWithIdentifier:@"LoginViewController"];
        [self presentViewController:vc animated:YES completion:nil];
    }
    
    if (sender.tag == 0){
        
        VC_INIT_WITH_STORYBOARD(news, NewsViewController, vc);
        vc.mainColor = HEXCOLOR(0x9ADC8E);vc.str_title = @"Found";
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (sender.tag == 1){
        DDQRCodeViewController *vc = [[DDQRCodeViewController alloc] initWithScanCompleteHandler:^(NSString *url) {
            NSLog(@"扫描 --- %@",url);
        }];
        [self presentViewController:vc animated:YES completion:nil];
    }else if (sender.tag == 2){
        
        VC_INIT_WITH_STORYBOARD(memory, MemoryViewController, vc);
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (sender.tag == 3){
        VC_INIT_WITH_STORYBOARD(battery, BatteryViewController, vc);
        [self.navigationController pushViewController:vc animated:YES];
    }else if (sender.tag == 4){
        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        
        if([[UIApplication sharedApplication] canOpenURL:url]) {
            
            NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
            [[UIApplication sharedApplication] openURL:url];
        }

    }else if (sender.tag == 5){
        VC_INIT_WITH_STORYBOARD(Tools, HHToolsViewController, vc);
        [self.navigationController pushViewController:vc animated:YES];
    }else if (sender.tag == 6){
        VC_INIT_WITH_STORYBOARD(speed, WifiSpeedController, vc);
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        VC_INIT_WITH_STORYBOARD(Main, ScreenTestController, vc);
        [self.navigationController pushViewController:vc animated:YES];
    }
        
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [MJUserModel registerSubclass];
    if ([MPWeChat stander].m_isLogin) {
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"first"]) {
            
            [self findUserData];
        }else{
            
            [self createUserModel];
        }
    }
}
- (void)findUserData{
    
    AVQuery *query = [AVQuery queryWithClassName:@"User_list"];
    NSString *objcid = [[NSUserDefaults standardUserDefaults] objectForKey:@"first"];
    [query getObjectInBackgroundWithId:objcid block:^(AVObject * _Nullable object, NSError * _Nullable error) {
        MJUserModel *model = (MJUserModel *)object;
        _userModel = model;
        [_imgv_head sd_setImageWithURL:[NSURL URLWithString:model.head_img.url]];
        _lab_username.text = model.name;
    }];
}
- (void)createUserModel{
    
    MJUserModel *model = [MJUserModel object];
    NSLog(@"------ %@",model.objectId);
    model.user_id = @"";
    model.name = NSLocalizedStringFromTable(@"Tomi", @"morePlist", nil);
    model.phoneNum = NSLocalizedStringFromTable(@"nol", @"morePlist", nil);
    model.sex = NSLocalizedStringFromTable(@"man", @"morePlist", nil);
    model.adrs = NSLocalizedStringFromTable(@"nol", @"morePlist", nil);
    model.adrs_now = NSLocalizedStringFromTable(@"nol", @"morePlist", nil);
    model.birthday = NSLocalizedStringFromTable(@"nol", @"morePlist", nil);
    model.height = NSLocalizedStringFromTable(@"nol", @"morePlist", nil);
    model.school_record = NSLocalizedStringFromTable(@"nol", @"morePlist", nil);
    model.enmotion = NSLocalizedStringFromTable(@"nol", @"morePlist", nil);
    model.signature = NSLocalizedStringFromTable(@"nol", @"morePlist", nil);
    UIImage *image = [UIImage imageNamed:@"user_head_df"];
    NSData *imageData=UIImageJPEGRepresentation(image,0.6);
    AVFile *file = [AVFile fileWithName:@"more_head_df.png" data:imageData];
    model.head_img = file;
    [model saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
        NSLog(@"------ %@",model.objectId);
        [[NSUserDefaults standardUserDefaults] setObject:model.objectId forKey:@"first"];
        
    }];
    _userModel = model;
    _lab_username.text = model.name;
    _imgv_head.image = image;
}
//登陆
- (IBAction)loginAction:(UIButton *)sender {
    if ([MPWeChat stander].m_isLogin) {
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"mine" bundle:nil];
        MJMyMsgController *vc = [sb instantiateViewControllerWithIdentifier:@"MJMyMsgController"];
        vc.userModel = _userModel;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"login" bundle:nil];
        LoginViewController *vc = [sb instantiateViewControllerWithIdentifier:@"LoginViewController"];
        [self presentViewController:vc animated:YES completion:^{
            
        }];
    }
}
//手机型号
- (IBAction)phoneModel:(id)sender {
}
//硬件信息
- (IBAction)phoneSystemMessages:(UIButton *)sender {
    
    VC_INIT_WITH_STORYBOARD(Main, HardwareController, vc);
    [self.navigationController pushViewController:vc animated:YES];
}
//意见反馈
- (IBAction)feedback:(id)sender {
    
    [[UIPasteboard generalPasteboard] setString:@"759120403@qq.com"];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto:759120403@qq.com"]];
}


-(void)clickAnimation{
    
    UIView *view = [[UIView alloc] initWithFrame:(CGRect){0,0,140,140}];
    view.center = (CGPoint){__kwidth/2,180};
    view.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.3];
    [self.view addSubview:view];
    view.layer.cornerRadius = 70;
    view.layer.borderColor = [UIColor whiteColor].CGColor;
    view.layer.borderWidth = 1;
    
    UILabel *label = [[UILabel alloc] initWithFrame:(CGRect){0,0,140,140}];
    label.center = (CGPoint){__kwidth/2,180};
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:20];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = LOC_STR(@"Mobile Doctor");
    [self.view addSubview:label];
    
    [UIView animateWithDuration:2 animations:^{
        view.transform=CGAffineTransformScale(view.transform, 1.4, 1.4);
        view.alpha=0;
    } completion:^(BOOL finished) {
        [view removeFromSuperview];
        [label removeFromSuperview];
    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
